<template>
  <demo-content :title="title">
    <canvas ref="canvasRef" width="600" height="400"></canvas>
  </demo-content>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { drawGrid, ellipse, line, ring, text } from "./utils";
import _ from "lodash";

const title = "绘制表盘";
// 指定组件上的属性
defineOptions({ title });

const canvasRef = ref<HTMLCanvasElement>();
onMounted(() => {
  const canvas = canvasRef.value!;
  const ctx = canvas.getContext("2d")!;
  drawGrid(ctx, { stepx: 10, stepy: 10 });
  const x = 300;
  const y = 200;
  const outerR = 180;
  const markOutR = 160;
  const markInR = 150;
  ring.draw(ctx, {
    x,
    y,
    outerR,
    innerR: markOutR,
    fillStyle: "#a5a9d360",
  });
  ring.draw(ctx, {
    x,
    y,
    outerR: markOutR,
    innerR: markInR,
    fillStyle: "#a5a9d330",
  });
  const dRadian = Math.PI / 64;
  for (let i = 0; i < 128; ++i) {
    const dr = markOutR - markInR;
    const radian = dRadian * i * -1;
    const x1 = x + markOutR * Math.cos(radian);
    const y1 = y + markOutR * Math.sin(radian);
    const showDigit = i % 8 === 0;
    const subL = showDigit ? 0 : dr / 2;
    const x2 = x + (markInR + subL) * Math.cos(radian);
    const y2 = y + (markInR + subL) * Math.sin(radian);
    line.draw(ctx, { x1, y1, x2, y2, strokeStyle: "#00b8" });
    if (showDigit) {
      const tr = markInR - 10;
      const tx = x + tr * Math.cos(radian) - 8;
      const ty = y + tr * Math.sin(radian) + 3;
      text.draw(ctx, {
        text: _.toString(Math.ceil((i * 90) / 32)),
        x: tx,
        y: ty,
        shadowColor: "gray",
        shadowOffsetX: 3,
        shadowOffsetY: 3,
        shadowBlur: 6,
        fontSize: 11,
        fillStyle: "blue",
      });
    }
  }
  ellipse.draw(ctx, {
    x,
    y,
    radiusX: 10,
    fillStyle: "skyblue",
    strokeStyle: "gray",
  });
  const targetX = x + outerR * Math.cos(Math.PI / -4);
  const targetY = y + outerR * Math.sin(Math.PI / -4);
  ellipse.draw(ctx, {
    x: targetX,
    y: targetY,
    radiusX: 5,
    fillStyle: "#ff08",
    strokeStyle: "#0008",
  });
  line.draw(ctx, {
    x1: x,
    y1: y,
    x2: targetX,
    y2: targetY,
    strokeStyle: "orange",
    lineWidth: 1,
  });
});
</script>

<style src="./default.css" scoped></style>
